package cz.uhk.max.log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class FileLogger implements Logger {

	private File logFile;
	private boolean finished = false;
	private String name;
	
	public FileLogger(String name) {
		try {
			this.name = name;
			this.logFile = File.createTempFile(this.name, "log");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String getName() {
		return name;
	}
	
	public synchronized void log(String text) {
		try {
			PrintWriter writer = 
				new PrintWriter(new FileWriter(logFile, false));
			writer.println(text);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public synchronized String read() {
		try {
			BufferedReader reader = 
				new BufferedReader(new FileReader(logFile));
			String progress = reader.readLine();
			reader.close();
			return progress;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void clear() {
		while (logFile.exists()) {
			logFile.delete();
		}
		finished = true;
	}

	public boolean isFinished() {
		return finished;
	}

}